
import { selectMasses } from '@/services/api/api-masses';
import { DownloadOutlined } from '@ant-design/icons';
import { ModalForm, ProFormCascader } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import {
    Alert,
    Button,
    Cascader,
    Descriptions,
    Divider,
    Image,
    message,
    Space,
    Spin,
    Tag,
    Typography,
    Upload,
    UploadFile,
} from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';

interface DetailsMassesProps {
    id: string;
    name: string;
    onRefurbish: () => void;
}

const DetailsMasses: React.FC<DetailsMassesProps> = ({ id, name, onRefurbish }) => {
    const access = useAccess();

    const [details, setDetailsState] = useState<MassesData.MassesDetails>();

    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewData, setPreviewData] = useState<{
        id: string;
        name: string;
        mimeType: string;
        url?: string;
    }>();
    const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
    const [previewLoading, setPreviewLoading] = useState(true);

    const [visible, setVisible] = useState(false);
    const [agreed, setAgreed] = useState(false);

    const handleOpenDrawer = () => {
        setVisible(true);
    };

    const handleCloseDrawer = () => {
        setVisible(false);
    };

    const handleAgree = () => {
        setAgreed(true);
        setVisible(false);
    };

    const maskName = (name) => {
        if (!name) return '';
        const nameParts = name.split('');
        const maskedName = `${nameParts[0]}${'*'.repeat(nameParts.length - 1)}`;
        return maskedName;
    };

    const maskPhone = (phone) => {
        if (!phone) return '';
        return `${phone.substring(0, 3)}****${phone.substring(7)}`;
    };

    const getWindowSize = () => ({
        innerHeight: window.innerHeight,
        innerWidth: window.innerWidth,
    });
    const [windowSize, setWindowSize] = useState(getWindowSize());
    const handleResize = () => {
        setWindowSize(getWindowSize());
    };
    useEffect(() => {
        // 监听
        window.addEventListener('resize', handleResize);
        // 销毁
        return () => window.removeEventListener('resize', handleResize);
    });

    const iframeRef = useRef(null);

    const handleLoad = () => {
        console.log('加载完成');
        setPreviewLoading(false);
    };
    useEffect(() => {
        const iframe = iframeRef.current;
        iframe?.addEventListener('load', handleLoad);
        return () => {
            iframe?.removeEventListener('load', handleLoad);
        };
    }, [previewOnlineUrl]);

    /**
     * 获取 详情
     * @param key
     */
    const loadSubmitDetails = async () => {
        try {
            const response = await selectMasses({ id });
            if (response.code === 0) {
                setDetailsState(response.data);
                console.log('=======', details?.cascaderAssignOrganizations);
            }
        } catch (error) { }
    };



    return (
        <DrawerForm
            key="details_details_drawer_form"
            title={details?.title}
            drawerProps={{
                // maskClosable: false,
                destroyOnClose: true,
                width: 900,
            }}
            trigger={<a>{name}</a>}
            submitter={false}
            onOpenChange={(visible) => {
                if (visible) {
                    loadSubmitDetails();
                } else {
                    onRefurbish();
                }
            }}
        >
            <DrawerForm
                title="隐私保护策略"
                open={visible}
                onOpenChange={(visible) => {
                    if (visible) {
                        loadSubmitDetails();
                    } else {
                        handleCloseDrawer()
                        onRefurbish();
                    }
                }}
                onFinish={() => {
                    handleAgree()
                }}
            >
                <p>这是隐私保护策略的内容。请仔细阅读。</p>
            </DrawerForm>
            <Spin
                style={{
                    textAlign: 'center',
                }}
                spinning={details === undefined}
            >
                {details !== undefined && (
                    <>
                        {/* <Descriptions>
                            <Descriptions.Item label="爆料人信息"> <Button size='small'>点击查看</Button></Descriptions.Item>
                        </Descriptions> */}

                        {/* <Divider /> */}
                        {details?.title ? (
                            <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                {details?.title}
                            </Typography.Title>
                        ) : (
                            <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                暂无标题
                            </Typography.Title>
                        )}
                        <Descriptions>
                            {details?.name && (
                                <Descriptions.Item label="爆料人">
                                    {agreed ? details.name : (
                                        <>
                                            {maskName(details.name)}
                                            {/* <a type="link" onClick={handleOpenDrawer} style={{ marginLeft: 10 }}>查看</a> */}
                                        </>
                                    )}
                                </Descriptions.Item>
                            )}
                            {details?.phone && (
                                <Descriptions.Item label="联系方式">
                                    {/* {agreed ? details.phone : maskPhone(details.phone)} */}
                                    {agreed ? details.phone : (
                                        <>
                                            {maskPhone(details.phone)}
                                            <a type="link" onClick={handleOpenDrawer} style={{ marginLeft: 10 }}>查看</a>
                                        </>
                                    )}
                                </Descriptions.Item>
                            )}
                            {/* <Descriptions.Item >
                                {!agreed && <a type="link" onClick={handleOpenDrawer} style={{ marginLeft: 10 }}>查看完整信息</a>}
                            </Descriptions.Item> */}
                        </Descriptions>
                        <Descriptions>
                            <Descriptions.Item label="爆料日期">
                                {details?.createdTime}
                            </Descriptions.Item>
                        </Descriptions>

                        <br />
                        {details?.content ? (
                            <div
                                dangerouslySetInnerHTML={{
                                    __html: `${details?.content}`,
                                }}
                            />
                        ) : (
                            <>暂无内容</>
                        )}

                        {details?.articleAttachments && details?.articleAttachments.length > 0 && (
                            <>
                                <Divider />
                                <div
                                    style={{
                                        textAlign: 'right',
                                    }}
                                >
                                    <Button
                                        type="primary"
                                        key="import"
                                        size="small"
                                        icon={<DownloadOutlined />}
                                        onClick={() => {
                                            details?.articleAttachments.forEach(function (item) {
                                                window.open(item.content, '_blank');
                                            });
                                        }}
                                    >
                                        全部下载
                                    </Button>
                                </div>

                                <Upload
                                    listType="picture"
                                    multiple
                                    fileList={details?.articleAttachments.map((item) => {
                                        return {
                                            uid: item.id,
                                            name: item.name,
                                            url: item.content,
                                            mimeType: item.mimeType,
                                            status: 'done',
                                        };
                                    })}
                                    showUploadList={{
                                        downloadIcon: (
                                            <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                <DownloadOutlined
                                                    style={{
                                                        marginRight: '10px',
                                                    }}
                                                />
                                                点击下载
                                            </div>
                                        ),
                                        showRemoveIcon: false,
                                        showDownloadIcon: true,
                                    }}
                                    onPreview={async (file: UploadFile) => {
                                        setPreviewData({
                                            id: file.uid,
                                            name: file.name,
                                            mimeType: file.mimeType,
                                            url: encodeURI(file.url),
                                        });
                                        setPreviewOpen(true);
                                    }}
                                />
                                <DrawerForm
                                    title={previewData?.name}
                                    drawerProps={{
                                        width: 900,
                                        destroyOnClose: true,
                                    }}
                                    open={previewOpen}
                                    onOpenChange={async (visible) => {
                                        if (visible) {
                                            if (
                                                previewData?.mimeType !== null &&
                                                previewData?.mimeType?.indexOf('image') > -1
                                            ) {
                                                //图片预览
                                            } else {
                                                setPreviewLoading(true);

                                                //   const response = await cuesAttachmentPreview({
                                                //     id: previewData?.id,
                                                //   });

                                                //   if (response.code === 0) {
                                                //     setPreviewOnlineUrl(response.data);
                                                //   } else {
                                                //     message.error('暂时无法预览');
                                                //     setPreviewLoading(false);
                                                //   }
                                            }
                                        } else {
                                            setPreviewOpen(false);
                                            setPreviewData(undefined);
                                            setPreviewOnlineUrl(undefined);
                                        }
                                    }}
                                    submitter={{
                                        searchConfig: {
                                            submitText: '下载',
                                        },
                                    }}
                                    onFinish={async (values) => {
                                        window.open(previewData?.url, '_blank');
                                    }}
                                >
                                    <Alert
                                        style={{
                                            marginBottom: 20,
                                        }}
                                        message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                        type="warning"
                                        showIcon
                                    />
                                    {previewData?.mimeType !== null &&
                                        previewData?.mimeType?.indexOf('image') > -1 ? (
                                        <Image width="100%" src={previewData?.url} />
                                    ) : (
                                        <Spin spinning={previewLoading}>
                                            <iframe
                                                ref={iframeRef}
                                                src={previewOnlineUrl}
                                                height={windowSize.innerHeight - 220}
                                                width="100%"
                                                frameBorder="0"
                                                // scrolling="false"
                                                allowFullScreen={true}
                                            // scrolling={'no'}
                                            />
                                        </Spin>
                                    )}
                                </DrawerForm>
                            </>
                        )}
                    </>
                )}
            </Spin>
        </DrawerForm >
    );
};

export default DetailsMasses;
